package za.ac.wits.elen7045.persistence.model;

import java.util.List;
import za.ac.wits.elen7045.persistence.PersistentObject;
import za.ac.wits.elen7045.persistence.exception.ObjectAlreadyExistException;
import za.ac.wits.elen7045.persistence.exception.ObjectNotFoundException;
import za.ac.wits.elen7045.persistence.util.ValidationUtilities;

public class Account extends PersistentObject {

	private ServiceProviderName serviceProviderType;
	private int accountNumber;
	private String accountOwnerName;
	private List<Credential> credentials;
	
	public Account(ServiceProviderName serviceProviderType, int accountNumber) {
		this.serviceProviderType = serviceProviderType;
		this.accountNumber = accountNumber;
	}
	
	public ServiceProviderName getServiceProviderType() {
		return serviceProviderType;
	}

	public int getAccountNumber() {
		return accountNumber;
	}
	
	public String getAccountOwnerName() {
		return accountOwnerName;
	}
	
	public void setAccountOwnerName(String accountOwnerName) {
		this.accountOwnerName = accountOwnerName;
	}
	
	public List<Credential> getCredentials() {
		return credentials;
	}

	public void setCredentials(List<Credential> credentials) {
		this.credentials = credentials;
	}
	
	public Credential getCredential(String name) {
		for (Credential credential : credentials) {
			if (ValidationUtilities.isEqual(credential.getName(), name)) {
				return credential;
			}
		}
		return null;
	}
	
	public void addCredential(String name, String value, boolean encrypted) {
		if (getCredential(name) != null) {
			throw new ObjectAlreadyExistException();
		} else {
			credentials.add(new Credential(name, value, encrypted));
		}
	}
	
	public void removeCredential(String name) {
		Credential persistedCredential = null;
		for (Credential credential : credentials) {
			if (ValidationUtilities.isEqual(credential.getName(), name)) {
				persistedCredential = credential;
				break;
			}
		}
		if (persistedCredential != null) {
			credentials.remove(persistedCredential);
		} else {
			throw new ObjectNotFoundException();
		}				
	}
	
}
